package com.atung.parking;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import com.atung.parking.request.AiRencheParkingRequest;
import lombok.extern.log4j.Log4j2;

import java.lang.reflect.Array;
import java.net.HttpCookie;
import java.time.Instant;
import java.util.*;

/**
 * @author Administrator
 */
@Log4j2
public class AiRencheParking {

    protected static String publicApiUrl = "http://www.airenche.com";
//    protected static String saveCarUrl = "/carshop/carAdd?tk=5381&sid=90766366";
//    private static String secretKey = "096e4ecd61535defb318becd39904fa2";

    protected static List<HttpCookie> getCookie(String secretKey) {
        long epochSecond = Instant.now().getEpochSecond();
        String sign = SecureUtil.md5(epochSecond + secretKey);
        List<HttpCookie> cookies = Arrays.asList(
                new HttpCookie("stamp", String.valueOf(epochSecond)),
                new HttpCookie("sign", sign)
        );
        log.info("请求的cookine{}", cookies);
        return cookies;
    }

    public static void saveCar(AiRencheParkingRequest req) {

        System.setProperty("jsse.enableSNIExtension", "false");
// 1. 拼 URL
        String url = "https://www.airenche.com/carshop/CarAdd"
                + "?tk=5381&sid=" + req.getSid();
        Map<String, Object> form1 = BeanUtil.beanToMap(req);
        Map<String, Object> form = new LinkedHashMap<>();
        form1.forEach((k, v) -> form.put(k, convert(v)));
        log.info("请求参数{}", form);
// 3. 发 GET
        try {
            String result = HttpRequest.get(url.trim())
                    .setFollowRedirects(true)
                    .header("Host", "www.airenche.com")
                    .header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                    .cookie(getCookie(req.getSecretKey()))// 把 Cookie 头带上去
                    .form(form)
                    .execute()
                    .body();
            log.info("【响应】：" + result);
        } catch (Exception e) {
            log.info("请求出现异常了{}", e);
        }
    }
    private static Object convert(Object v) {
        if (v == null) {
            return null;
        }
        // 2. 集合
        if (v instanceof Iterable) {
            List<Object> list = new ArrayList<>();
            ((Iterable<?>) v).forEach(e -> list.add(convert(e)));
            return list.toString();
        }
        // 4. 普通值直接返回
        return v;
    }
}
